package com.example.syn.test;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.accloud.cloudservice.AC;

import com.accloud.cloudservice.PayloadCallback;
import com.accloud.service.ACException;

import com.accloud.service.ACMsg;
import com.accloud.service.ACObject;
import com.accloud.service.ACProduct;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SYN on 2017/11/21.
 */
public class ProductActivity extends Activity{
    private final String SUB_DOMAIN_NAME="demo";
    private final String URL="http://192.168.0.146:8080";
    private ListView deviceList;
    private TextView  add_device;
    ArrayList<ACObject> userData=new ArrayList<ACObject>();
    ArrayList<Integer> groupIdData;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);
        userData=null;
       //  fetchProducts();  //获取主域信息
       // fetchSubProducts();  //获取产品子域信息
      //  modifyUserGroupId();
        getDeviceList();
        deviceList=(ListView) findViewById(R.id.lvdevice);
        add_device= (TextView) findViewById(R.id.add_device);
        add_device.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(ProductActivity.this,AddDeviceActivity.class);
                startActivity(intent);
            }
        });

      }

    /**
     * 向云端发送消息，获取设备列表
     */
    private void getDeviceList(){
        ACMsg req = new ACMsg();
        req.setName("getDeviceList");
        req.put("username","18251887993");

        AC.sendToService("DEVICEDEMO", 2, req, new PayloadCallback<ACMsg>() {
                   @Override
                   public void success(ACMsg acMsg) {
                       Log.i("mytag","获取设备成功");

                        ArrayList<ACObject> deviceData= (ArrayList<ACObject>) acMsg.get("deviceList"); //设备列表数据，包括设备Id 和 设备所对应的组号
                         groupIdData=acMsg.get("groupIds");  //获取所登录用户所在的所有分组
                         userData= (ArrayList<ACObject>) acMsg.get("userList");
                        Log.i("mytag",deviceData.toString());
                       deviceList.setAdapter(new Adapter(getApplicationContext(),deviceData,groupIdData));

                   }
                   @Override
                   public void error(ACException e) {


                       System.out.println("异常"+e);
                       Log.i("mytag","获取设备失败");
                   }
               });

    }


    /**
     * ListView数据源 Adapter
     */
    private class Adapter extends BaseAdapter{

        int selectedDeviceId;  //用于请求消息的设备Id
        int SelectedGroupId;  //用于请求消息的设备所属于的组号
        private Context context;
        private ArrayList<ACObject> data; //设备列表数据，包括设备Id 和 设备所对应的组号
        private ArrayList<Integer> groupIdData; //登录用户所在的所有分组

        public Adapter(Context context,ArrayList<ACObject> data,ArrayList<Integer> groupIdData){
            this.context=context;
            this.data=data;
            this.groupIdData=groupIdData;
        }

        private class ViewHolder{
            public TextView deviceId;
            public Button btnAck;
            public Spinner spinnerGroupId;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView= LayoutInflater.from(context).inflate(R.layout.layout_lv,null);

                viewHolder=new ViewHolder();
                viewHolder.deviceId=(TextView)convertView.findViewById(R.id.tvDevice);
                viewHolder.spinnerGroupId=(Spinner)convertView.findViewById(R.id.spinerGroup);
                viewHolder.btnAck=(Button)convertView.findViewById(R.id.btnACK);

                //spiner的默认值，即设备的原始组号
                int defaultGroupId=Integer.valueOf(String.valueOf(data.get(position).get("groupId")));

                //spinner下拉框绑定的所有数据
                ArrayList<Integer> groupIdList=new ArrayList<>();
                groupIdList.add(defaultGroupId);
                for(int i=0;i<groupIdData.size();i++) {
                    int tempGroupId=Integer.valueOf(String.valueOf(groupIdData.get(i)));
                    if(defaultGroupId!=tempGroupId)
                    groupIdList.add(tempGroupId);
                }

                ArrayAdapter<Integer> adapter=new ArrayAdapter<Integer>(convertView.getContext(),android.R.layout.simple_spinner_item,groupIdList);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                viewHolder.spinnerGroupId.setAdapter(adapter);

                viewHolder.spinnerGroupId.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                        SelectedGroupId=Integer.valueOf(String.valueOf(parent.getItemAtPosition(position))); //获取组号
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                convertView.setTag(viewHolder);
            }
            else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.deviceId.setText(data.get(position).get("deviceId").toString());
            final int pos=position;
            viewHolder.btnAck.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectedDeviceId=Integer.valueOf(String.valueOf(data.get(pos).get("deviceId")));
                    System.out.println("设备："+selectedDeviceId+",对应的组号"+SelectedGroupId);

                    modifyGroupId(selectedDeviceId,SelectedGroupId);  //修改设备权限 即修改所在分组
                }
            });
            return convertView;
        }



        /**
         * 向云端发送请求消息，修改设备权限 即修改所在分组
         * @param deviceId  设备Id
         * @param groupId  设备组号
         */
        private void modifyGroupId(int deviceId,int groupId)
        {
            ACMsg req = new ACMsg();
            req.setName("updateDeviceGroupId");
            req.put("username","18251887993");
            req.put("deviceId",deviceId);
            req.put("groupId",groupId);
            AC.sendToService("DEVICEDEMO", 2, req, new PayloadCallback<ACMsg>() {
                @Override
                public void success(ACMsg acMsg) {
                    Log.i("mytag","修改权限成功");
                }
                @Override
                public void error(ACException e) {
                    Log.i("mytag","修改权限失败");
                }
            });
        }
    }


    /**
     * 获取产品子域信息
     */
    private void fetchSubProducts(){
        AC.productMgr().fetchProduct(SUB_DOMAIN_NAME, new PayloadCallback<ACProduct>() {
            @Override
            public void success (ACProduct acProduct) {
                Log.i("mytag","获取子域产品成功");
            }
            @Override
            public void error(ACException e) {

            }
        });

    }

    /**
     * 获取主域信息
     */
    private void fetchProducts(){
        AC.productMgr().fetchAllProducts(new PayloadCallback<List<ACProduct>>() {
            @Override
            public void success(List<ACProduct> acProducts) {
                Log.i("mytag","获取成功");
            }
            @Override
            public void error(ACException e) {
                Log.i("mytag","获取失败");
            }
        });

    }

    private void modifyUserGroupId(){
        ACMsg req=new ACMsg();
        req.setName("createGroup");
        req.put("username","18251887993");
        req.put("groupId",4);
        //req.put("permission",3);
        AC.sendToService("DEVICEDEMO", 2, req, new PayloadCallback<ACMsg>() {
            @Override
            public void success(ACMsg acMsg) {
                Log.i("mytag","修改user成功");
            }

            @Override
            public void error(ACException e) {
                Log.i("mytag","修改user失败");
            }
        });

    }
}

